#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-9-10'
# code is far away from bugs with the god animal protecting ~
"""
import random
import re

from flask import make_response, request, current_app, session, g

from info import redis_server, constants, db
from info.libs.yuntongxun import sms
from info.models import User
from info.response_code import RET
from info.utils.captcha.captcha import captcha
from info.utils.common import general_msg
from . import bp_passport as app


# 生成验证码
@app.route("/passport/image_code")
def get_verify_image():
	image_code_id = request.args.get("image_code_id")

	if not image_code_id:
		return general_msg(RET.PARAMERR, "未取到图片ID")

	# 生成验证码
	file_name, text, img = captcha.generate_captcha()

	try:
		redis_server.setex(constants.IMAGE_VERIFY_PREFIX + image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
	except Exception as e:
		current_app.logger.error(e)
		return general_msg(RET.DBERR)
	else:
		response = make_response(img)
		response.headers["Content-Type"] = "image/jpg"
		return response


# 发送短信验证码
@app.route("/passport/sms_code", methods=["POST"])
def get_sms_code():
	mobile = request.json.get("mobile")
	image_code = request.json.get("image_code")
	image_code_id = request.json.get("image_code_id")

	# print(mobile,image_code_id,image_code)

	if not all([mobile, image_code, image_code_id]):
		return general_msg(RET.PARAMERR)

	if not re.match(r"1[3-9]\d{9}$", mobile):
		return general_msg(RET.PARAMERR, "电话号码格式错误")

	try:
		server_image_code = redis_server.get(constants.IMAGE_VERIFY_PREFIX + str(image_code_id)).decode()
	except Exception as e:
		current_app.logger.error(e)
		return general_msg(RET.DBERR, "Redis错误")
	else:
		redis_server.delete(image_code_id)  # pass

	if image_code.lower() != server_image_code.lower():
		return general_msg(RET.DATAERR, "验证码错误")

	sms_code = "{:0>6d}".format(random.randint(1, 999999))
	# 注意： 测试的短信模板编号为1
	ccp = sms.CCP()
	try:
		print(
			sms_code)  # 此处发送验证码  # sms_status = ccp.send_template_sms('13826215467', [sms_code, 5], 1)  # print(sms_status)  # if sms_status == -1:  # 	raise Exception("第三方错误")
	except Exception as e:
		return general_msg(RET.THIRDERR, "验证码错误")

	try:
		redis_server.setex(constants.SMS_VERIFY_PREFIX + str(mobile), constants.SMS_CODE_REDIS_EXPIRES, sms_code)
	except Exception as e:
		current_app.logger.error(e)
		return general_msg(RET.DBERR)

	return general_msg(RET.OK)


# 注册接口
@app.route("/passport/register", methods=["POST"])
def register():
	get_para = request.json
	# 获取参数
	if get_para:
		mobile = get_para["mobile"]
		smscode = get_para["smscode"]
		password = get_para["password"]
	else:
		return general_msg(RET.PARAMERR)

	# 检查参数是否齐全csrf_token
	if not all([mobile, smscode, password]):
		return general_msg(RET.PARAMERR)

	# 1电话是否正确
	if not re.match(r"1[3-9]\d{9}$", mobile):
		return general_msg(RET.PARAMERR, "电话号码错误")

	# 2短信验证码是否正确
	smscode_server = None
	try:
		smscode_server = redis_server.get(constants.SMS_VERIFY_PREFIX + str(mobile)).decode()
	except Exception as e:
		current_app.logger.error(e)
		return general_msg(RET.DBERR, "查询REDIS错误")

	if smscode != smscode_server:
		return general_msg(RET.PARAMERR, "短信验证码错误")

	# 3密码是否正确
	if not re.match(r"\w{" + str(constants.USER_PASSWD_LENGTH) + ",}$", password):
		return general_msg(RET.PARAMERR, "输入的密码错误")

	try:
		user = User.query.filter_by(mobile=mobile).first()
	except Exception as e:
		current_app.logger.error(e)
		return general_msg(RET.DBERR)

	if user:
		return general_msg(RET.USERERR, "用户已存在,请重新输入")

	# 如果都正确则：
	# 1、在数据库中增加用户
	user = User()
	user.mobile = mobile
	user.password = password
	user.nick_name = mobile
	try:
		db.session.add(user)
		db.session.commit()
	except Exception as e:
		db.session.rollback()
		current_app.logger.error(e)
		return general_msg(RET.DBERR, "MySql数据库错误")

	# 2、删除session中的短信认证
	try:
		redis_server.delete(constants.SMS_VERIFY_PREFIX + str(mobile))
	except Exception as e:
		current_app.logger.error(e)
		return general_msg(RET.DBERR, "删除REDIS数据错误")

	# 3、增加session中的用户id，昵称，电话
	session["user_id"] = user.id
	session["mobile"] = user.mobile
	session["nick_name"] = user.nick_name

	return general_msg(RET.OK)


# 登陆验证
@app.route("/login", methods=["POST"])
def login():
	get_para = request.json
	# 获取参数
	if get_para:
		mobile = get_para["mobile"]
		password = get_para["password"]
	else:
		return general_msg(RET.PARAMERR)

	if not re.match(r"1[3-9]\d{9}$", mobile):
		return general_msg(RET.PARAMERR, "电话号码错误")

	user = None
	try:
		user = User.query.filter_by(mobile=mobile).first()
	except Exception as e:
		return general_msg(RET.DBERR, "MySql查詢错误")
	else:
		if user is None or not user.check_password(password):
			return general_msg(RET.LOGINERR)

	# 用户登录成功,写入Session信息
	session["user_id"] = user.id
	session["mobile"] = user.mobile
	session["nick_name"] = user.nick_name

	return general_msg(RET.OK)


# 退出验证
@app.route("/logout", methods=["POST"])
def logout():
	try:
		session.pop("user_id", None)
		session.pop("mobile", None)
		session.pop("nick_name", None)
		session.pop("is_admin", None)
	except Exception as e:
		return general_msg(RET.SESSIONERR, "用户已退出")

	return general_msg(RET.OK)


if __name__ == '__main__':
	pass
